//
//  AIMaeketController.m
//  aixianfeng
//
//  Created by 李江波 on 2016/12/22.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

#import "AIMaeketController.h"
#import "AILeftCell.h"
#import "AIRightCell.h"
#import "LEEHTTPManager.h"
#import "AICategoriesLeftModel.h"
#import "AIProductsRightModel.h"
#import "UIViewController+SLHUD.h"

@interface AIMaeketController ()<UITableViewDataSource,UITableViewDelegate,CAAnimationDelegate>

@property (nonatomic, weak) UITableView *leftTableView;

@property (nonatomic, weak) UITableView *rightTableView;

@property (nonatomic,strong) NSArray <AICategoriesLeftModel *> *cateModelArray;
@property (nonatomic,strong) NSMutableArray <AIProductsRightModel *> *proModelArray;


/**
 判断是否左侧cell点击了
 */
@property (nonatomic, assign) BOOL  isLeftClick;
@end


static NSString *left_id = @"hh";
static NSString *right_id = @"ll";
static NSString *right_id_xf = @"llrr";

@implementation AIMaeketController


- (void)viewDidLoad {
    [super viewDidLoad];
    // 显示数据
    [self loadDate];
    // 显示左右的tableview
    [self setupTableView];
    //注册通知
    [self registerNotification];
    
    
}





#pragma mark - 注册通知
- (void)registerNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementNotification:) name:kIncrementNotification object:nil];
}

#pragma mark - 点击增加的方法
- (void)incrementNotification:(NSNotification *)noti {
    CGPoint beginPiont = [noti.userInfo[@"point"] CGPointValue];
    CGRect iconBounds = [noti.userInfo[@"iconBounds"] CGRectValue];
    
    UIImageView *animationView = [[UIImageView alloc] initWithImage:noti.userInfo[@"iconImage"]];
    animationView.center = beginPiont;
    animationView.bounds = iconBounds;
    [self.view addSubview:animationView];
    
    CGPoint controlPoint = CGPointMake(beginPiont.x + 50, beginPiont.y - 80);
    CGPoint endPoint = CGPointMake(LeeScreenWidth - 120, LeeScreenHeight - 50);
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:beginPiont];
    
    [bezierPath addQuadCurveToPoint:endPoint controlPoint:controlPoint];
    
    
    // 创建关键帧动画中心点
    CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
//    positionAnimation.duration = 1;
    
    positionAnimation.path = bezierPath.CGPath;
    
    // 改变图片的大小
    CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    transformAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    transformAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DScale(CATransform3DIdentity, 0.2, 0.2, 1)];
    // 加入动画组
    CAAnimationGroup *groupAnimation = [CAAnimationGroup animation];
    groupAnimation.animations = @[positionAnimation,transformAnimation];
    groupAnimation.duration = 0.8;
    groupAnimation.delegate = self;
    
    [groupAnimation setValue:animationView forKey:@"imageView"];
    
    
     [animationView.layer addAnimation:groupAnimation forKey:@"cartParabola"];
}

#pragma mark - 动画代理
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    
    // 1. 获取到imageView
    UIImageView *animationView = [anim valueForKey:@"imageView"];
    
    [animationView removeFromSuperview];
}


#pragma mark - 加载数据 -

- (void)loadDate {
    
    NSString *urlStr = @"http://iosapi.itcast.cn/loveBeen/supermarket.json.php";
    NSDictionary *parameter = @{@"call":@"5"};
    
    [self showHint:@"hehe"];
    [[LEEHTTPManager share] request:POST UrlString:urlStr parameters:parameter finshed:^(id responseObject, NSError *error) {
        
        [self hideHud];
        NSDictionary *responDict = (NSDictionary *)responseObject;
        
        NSDictionary *dataDict = responDict[@"data"];
        
        // 左边数据模型
        NSArray *cateArray = dataDict[@"categories"];
        NSArray <AICategoriesLeftModel *> *cateModel = [NSArray yy_modelArrayWithClass:[AICategoriesLeftModel class] json:cateArray];
        _cateModelArray = cateModel;
        
        // 右边数据模型
        NSDictionary *proDict = dataDict[@"products"];
        
        NSMutableArray *proArrayM = [NSMutableArray array];
      
        [cateArray enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
            NSArray *proId = proDict[obj[@"id"]];
            NSMutableArray *arrayM = [NSMutableArray array];
            for (NSDictionary *proDictModel in proId) {
                
                AIProductsRightModel *proModel = [AIProductsRightModel productWithDic:proDictModel];
                
                [arrayM addObject:proModel];
                
            }
            _cateModelArray[idx].array = arrayM;
            [arrayM removeAllObjects];
            
        }];
        [self.leftTableView reloadData];
        [self.rightTableView reloadData];
        
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        [_leftTableView selectRowAtIndexPath:indexpath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
       
        _proModelArray = proArrayM.copy;
 
    }];
}

#pragma mark - 显示界面 -
- (void)setupTableView
{
#pragma mark - 左边 -
    UITableView *leftTableView = [[UITableView alloc] init];
    leftTableView.dataSource = self;
    leftTableView.delegate = self;
    [leftTableView registerClass:[AILeftCell class] forCellReuseIdentifier:left_id];
    [self.view addSubview:leftTableView];
    
    [leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.view);
        make.width.mas_equalTo(100);
    }];
    _leftTableView = leftTableView;
    
#pragma mark - 右边 -
    UITableView *rightTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    rightTableView.dataSource = self;
    rightTableView.delegate = self;
    rightTableView.rowHeight = 80;
    
    //设置组头
    rightTableView.sectionFooterHeight = 0;
    
    UINib *nib1 = [UINib nibWithNibName:@"AIRightCell" bundle:nil];//
    UINib *nib2 = [UINib nibWithNibName:@"AIRightXFCell" bundle:nil];

    [rightTableView registerNib:nib1 forCellReuseIdentifier:right_id];
    [rightTableView registerNib:nib2 forCellReuseIdentifier:right_id_xf];
    
    [self.view addSubview:rightTableView];
    
    [rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.view);
        make.left.equalTo(leftTableView.mas_right);
        make.top.equalTo(self.view).mas_offset(64);
    }];
    _rightTableView = rightTableView;
    
}


#pragma mark - 数据源代理 -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == _leftTableView) {
        
        return 1;
    } else {
        
        return self.cateModelArray.count ;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == _leftTableView) {
        
        return self.cateModelArray.count;
    } else {

        return self.cateModelArray[section].array.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == self.rightTableView) {
        
        return 30;
    }else{
    
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTableView) {
        
        AILeftCell *cell = [tableView dequeueReusableCellWithIdentifier:left_id forIndexPath:indexPath];
        cell.textLabel.text = self.cateModelArray[indexPath.row].name;
        
        return cell;
    } else {
        
        AICategoriesLeftModel *model2 = self.cateModelArray[indexPath.section];
        AIProductsRightModel *model = model2.array[indexPath.row];
        
        if (!model.is_xf) {
            
            AIRightCell *cell = [tableView dequeueReusableCellWithIdentifier:right_id_xf forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;  
            cell.rigthMdel = model;
            return cell;
            
        }else {
            AIRightCell *cell = [tableView dequeueReusableCellWithIdentifier:right_id forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.rigthMdel = model;
            return cell;
        }
    }
}


#pragma mark - 设置组头 -
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        return nil;
    }else {
        UILabel *headerLabel = [[UILabel alloc] init];
        headerLabel.text = [NSString stringWithFormat:@"    %@",self.cateModelArray[section].name];
        headerLabel.font = [UIFont systemFontOfSize:14];
        headerLabel.tintColor = [UIColor colorWithWhite:0.5 alpha:1];
        headerLabel.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:0.5];
        return headerLabel;
    }
}

#pragma mark - 设置联动 -
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTableView) {
    
        // 点击了左侧cell
        _isLeftClick = YES;
        
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        
        [_rightTableView scrollToRowAtIndexPath:newPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _rightTableView) {
        // 如果左侧cell 被点击了, 右侧不执行这个方法
        if (_isLeftClick) {
            
            return;
        }
        
        NSArray *indexArray = [tableView indexPathsForVisibleRows];
        NSIndexPath *rightFirstPath = indexArray.firstObject;
        
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:rightFirstPath.section inSection:0];
        [_leftTableView selectRowAtIndexPath:newPath animated:NO scrollPosition:UITableViewScrollPositionTop];
    }
    
}

#pragma mark - 在右侧tableView 开始拖拽的时候, 把_isLeftClick修改为NO
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    if (scrollView == _rightTableView) {
        
        
        _isLeftClick = NO;
    }
}

@end
